package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"order_srv/models"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单创建
func (l *OrderAddLogic) OrderAdd(in *order.OrderAddRequest) (*order.OrderAddResponse, error) {
	//判断用户是否存在
	var user models.User
	user.ID = uint(in.UserId)
	if err := user.Show(); err != nil {
		logx.Info("该用户不存在", err)
		return nil, errors.New("该用户不存在")
	}
	//判断商品是否存在
	var good models.Good
	good.ID = uint(in.GoodsId)
	if err := good.Shoe(); err != nil {
		logx.Info("该商品不存在", err)
		return nil, errors.New("该商品不存在")
	}
	//判断库存是否充足
	if good.GoodsStock < in.Num {
		logx.Info("库存不足")
		return nil, errors.New("库存不足")
	}
	//创建订单
	orders := models.Order{
		UserId:      in.UserId,
		OrderNo:     uuid.NewString(),
		OrderPrice:  good.GoodsPrice * float64(in.Num),
		OrderStatus: 1,
		OrderPay:    1,
	}
	if err := orders.Create(); err != nil {
		logx.Info("订单创建失败", err)
		return nil, err
	}
	//创建订单商品
	orderGoods := models.OrderGood{
		OrderId:    int64(orders.ID),
		GoodsId:    in.GoodsId,
		GoodsTitle: good.GoodsTitle,
		GoodsImage: good.GoodsImage,
		GoodsNum:   in.Num,
	}
	if err := orderGoods.Create(); err != nil {
		logx.Info("订单商品创建失败", err)
		return nil, err
	}

	return &order.OrderAddResponse{
		OrderId: int64(orders.ID),
	}, nil
}
